import mongoose from 'mongoose';
import moment from 'moment';
import db from './db';
mongoose.Promise = global.Promise;

const SecondhandSchema = new mongoose.Schema({
    title: String,
    content: String, // 内容
    imgs: Array, // 附件图片
    category: String, // 所属分类
    price: Number,
    secCategory: String,
    createTime: Number,
    endTime: Number,
    creator: Object,
    creatorId: String,
    isBuy: Boolean, // 买还是卖
    opponent: Object, // 对方
    opponentId: String,
    status: {type: Number, default: 0}, // 0 等待接单；1 接单完成
    likeNum: {type: Number, default: 0},
    shareNum: {type: Number, default: 0},
    cmtNum: {type: Number, default: 0},
    viewNum: {type: Number, default: 0},
    schoolId: String, // 所属学校
});

SecondhandSchema.methods.saveSecondhand = function (secondhand, cb) {
    secondhand.createTime = moment().unix();
    this.model('secondhand').insertMany([secondhand], cb);
};

SecondhandSchema.methods.getSecondhands = function (query, cb) {
    const { current = 1, pageSize = 10, ...leftQuery } = query;
    const secondhandModel = this.model('secondhand');
    secondhandModel.count(leftQuery, function (err, count) {
        const hasMore = count / pageSize > current;
        secondhandModel.find(leftQuery).sort({createTime: -1}).skip((current - 1) * pageSize).limit(pageSize).exec((err, secondhands) => cb(err, secondhands, count, hasMore));
    });
};

SecondhandSchema.methods.getAllSecondhands = function (query, cb) {
    this.model('secondhand').find(query, { name: 1, _id: 0 }, cb);
};

SecondhandSchema.methods.getSecondhand = function (query, cb) {
    this.model('secondhand').findOne(query, cb);
};

SecondhandSchema.methods.updateSecondhand = function (secondhand, cb) {
    const _id = secondhand._id;
    delete secondhand._id;
    this.model('secondhand').findOneAndUpdate({ _id }, { $set: secondhand }, cb);
};

SecondhandSchema.methods.removeSecondhands = function (secondhandIds, cb) {
    this.model('secondhand').remove({ _id: { $in: secondhandIds } }, cb);
};

export default db.model('secondhand', SecondhandSchema);